package com.wenhai.spring.event;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.springframework.context.support.AbstractApplicationContext.*;

/**
 * 异步事件处理器示例
 *
 * @author wenhai
 * @date   2021/4/20
 */
public class AsyncEventHandlerDemo {
    public static void main(String[] args) {
        GenericApplicationContext context = new GenericApplicationContext();
        context.addApplicationListener(new MySpringEventListener());
        context.refresh();
        ApplicationEventMulticaster multicaster = context.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        if (multicaster instanceof SimpleApplicationEventMulticaster) {
            SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = (SimpleApplicationEventMulticaster) multicaster;
            ExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new CustomizableThreadFactory("my-spring-event-thread-pool"));
            simpleApplicationEventMulticaster.setTaskExecutor(executorService);
            simpleApplicationEventMulticaster.addApplicationListener((ApplicationListener<ContextClosedEvent>) event -> executorService.shutdown());
        }
        context.publishEvent(new MySpringEvent("Hello, World"));
        context.close();
    }
}
